const express = require('express');
const router = express.Router();
const mysql = require('mysql')
const db = require('../../sql/db')
const $sql = require('../../sql/sqlMap')

const connection = mysql.createConnection(db.mysql,);
connection.connect();
const sql2 = $sql.management.AgreeToStudentRequest;
const sql1 = $sql.management.creditUp;

router.post('/:id', (req, res, next) => {
    console.log(req.body)
    let sid = req.body.sid;
    let credit = req.body.credit;
    let creditNumber = req.body.creditNumber;
    let sum = parseInt(credit) + parseInt(creditNumber)
    connection.beginTransaction(err => {
        if (err) {
            console.log(err)
            return
        }
        connection.query(sql1, [sum, sid], (err, result) => {
            if (err) {
                // 删除失败数据回滚
                connection.rollback(() => {
                })
                return
            }
            connection.query(sql2, [sum, req.params.id], (err, result) => {
                if (err) {
                    // 更新失败
                    connection.rollback(() => {
                    })
                    return
                }
                connection.commit(err => {
                    if (err) {
                        console.log('提交事务失败')
                    }
                })
                res.json({
                    status: '0',
                    msg: '申请通过',
                    result: result
                })
            })
        })
    })
});

module.exports = router;
